import { io } from 'socket.io-client';
import { chromium } from "playwright";
import XhsAgent from './platforms/xhs.js';
import path from 'path';
import fs from 'fs';
import logger from './logger.js';

// Define __dirname for ES modules
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const dirPath = path.join(__dirname, '..');
const config = JSON.parse(fs.readFileSync(path.join(__dirname, 'config.json'), 'utf8'));

// Launch a Chromium browser
const browser = await chromium.launch({ 
  args: ['--disk-cache-size=10000000'], // 设置缓存大小（字节）
  headless: false // Set headless to true if you don't want a visible browser
}); 

const context = await browser.newContext({
  ignoreHTTPSErrors: true,
  bypassCSP: true,
  // 禁用缓存
  storageState: fs.existsSync(`${dirPath}/auth/auth.json`) ?  `${dirPath}/auth/auth.json` : {},    
});

// const REMOTE_HOST_URI = 'http://127.0.0.1:3001';
// const REMOTE_HOST_URI = 'http://172.20.50.49:3001';
const REMOTE_HOST_URI = 'http://119.253.65.194:3001';
config["remote_host_url"] = REMOTE_HOST_URI;

const socket = io(`${REMOTE_HOST_URI}`, { reconnection: false });

let xhsAgent = null;

async function startXhsAgent() {
  const page = await context.newPage();

  xhsAgent = new XhsAgent(page, config);
  xhsAgent.on('hot-feed', (feed) => {
    // console.log("sent:", feed);
    socket.emit('hot-feed', feed);
  });

  try {
    await xhsAgent.start();
    // Save the login state  
    await context.storageState({    
      path: `${dirPath}/auth/auth.json`, 
    });
    
    await xhsAgent.run();
  } catch (error) {
    logger.error("catched error: ", error.message);
    process.exit(-1);
  }

}
socket.on('connect', async () => {
  logger.info('Connected to server');
  // Start XhsAgent
  if (!xhsAgent) {
    await startXhsAgent();
  }
});

socket.on('disconnect', async() => {
  if (xhsAgent) {
    xhsAgent.stop();
    xhsAgent = null;
  }
  await browser.close();
  logger.info('Disconnected from server');

  process.exit(0);
});

socket.on('message', (data) => {
  logger.debug('Received message:', data);
});

socket.on('connect_error', (err) => {
  logger.error('Connection error:', err.message);
});